
import json
import requests
import xmltodict

class Q_Jenkins():
    def __init__(self, host=None, user=None, passw=None):
        self.host = host
        self.user = user
        self.passw = passw

    def req_via_jenkins_api(self, api_url):
        from requests.auth import HTTPBasicAuth
        auth = HTTPBasicAuth(self.user, self.passw)
        resp = requests.get(url=api_url, auth=auth)
        print(resp.status_code)
        return resp.text

    def get_computer_config(self, node_name):
        computer_config_api = "http://" + self.host + "/computer/{}/config.xml".format(node_name)
        config_xml = self.req_via_jenkins_api(computer_config_api)
        config_json = xmltodict.parse(config_xml)
        return config_json

class SoclabNode():
    def __init__(self, jenkins, nodeName):
        self.jenkins = jenkins
        self.nodeName = nodeName
        self.node_config = self.jenkins.get_computer_config(self.nodeName)

    def get_workspace(self):
        dict_workspace = {}
        workspace_info = self.node_config["slave"]["nodeProperties"]["hudson.slaves.EnvironmentVariablesNodeProperty"]["envVars"]["tree-map"]["string"]
        for k_index in range(int(len(workspace_info)/2)):
            dict_workspace[workspace_info[k_index*2]] = workspace_info[k_index + 1]
        return dict_workspace
    
    def get_host(self):
        return self.node_config["slave"]["launcher"]["host"]

if __name__ == "__main__":
        q_jenkins = Q_Jenkins("atf-ci.dynamic.nsn-net.net:8080", "qiuchen", "QWe@1995118")
        t1 = SoclabNode(q_jenkins, "Test_executor_env_1")
        print(t1.get_workspace())
        print(t1.get_host())
        
